﻿from fastapi import APIRouter, HTTPException
from fastapi.responses import JSONResponse
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.sts.v20180813 import sts_client, models
from src.config import settings
from src.utils.logger import logger
import json
import time

router = APIRouter()

@router.get("/get-temp-credentials",
            summary="",
            response_description="临时访问凭证，包含临时密钥和会话令牌")
async def get_temp_credentials():

    try:
        cred = credential.Credential(settings.COS_SECRET_ID, settings.COS_SECRET_KEY)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "sts.tencentcloudapi.com"
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = sts_client.StsClient(cred, settings.COS_REGION, clientProfile)

        req = models.GetFederationTokenRequest()
        req.Name = "excel_filler_temp_user"
        req.DurationSeconds = 1800  # 30分钟有效期

        #
        policy_statement = {
            "version": "2.0",
            "statement": [

                {
                    "action": [
                        "ci:CreateDocProcessJobs"
                    ],
                    "effect": "allow",
                    "resource": [
                        f"qcs::ci:{settings.COS_REGION}:uid/{settings.COS_APP_ID}:bucket/{settings.COS_BUCKET_NAME}/*"
                    ]
                }
            ]
        }
        req.Policy = json.dumps(policy_statement)

        logger.info("正在请求临时访问凭证...")
        resp = client.GetFederationToken(req)
        logger.info("成功获取临时访问凭证")

        start_time = int(time.time())

        # 返回字段名与前端一致
        return JSONResponse(content={
            "TmpSecretId": resp.Credentials.TmpSecretId,
            "TmpSecretKey": resp.Credentials.TmpSecretKey,
            "Token": resp.Credentials.Token,
            "StartTime": start_time,
            "ExpiredTime": resp.ExpiredTime
        })

    except Exception as e:
        error_msg = f"获取临时访问凭证失败: {str(e)}"
        logger.error(error_msg)
        raise HTTPException(status_code=500, detail=error_msg)